package com.amos.base.repository;

import com.amos.base.base.BaseEntity;
import com.amos.base.base.Mapper;
import com.amos.base.constant.SysConfig;
import com.amos.base.exception.ApplicationException;
import com.amos.base.util.NullUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author Amos
 * @ClassName AbstractRepository
 * @Description TODO
 * @Date 2018/12/22 22:37
 * @VERSION 1.0
 **/
@Transactional(readOnly = true, rollbackFor = ApplicationException.class)
public class AbstractRepository<T extends BaseEntity, E extends Mapper> implements Repository<T> {

    @Autowired
    protected E mapper;

    /**
     * 保存数据字段
     *
     * @param entity
     * @return
     */
    @Override
    public int save(T entity) {
        if (NullUtils.isEmpty(entity)) {
            return 0;
        }
        if (entity.isNew()) {
            return this.insert(entity);
        } else {
            return this.updateByPrimaryKeySelective(entity);
        }
    }

    /**
     * 标记删除
     *
     * @param id
     * @return
     */
    @Override
    public int deleteByPrimaryKey(String id) {
        T entity = this.selectByPrimaryKey(id);
        entity.setIsDelete(SysConfig.IS_DELETE_YES);
        return this.updateByPrimaryKeySelective(entity);
    }

    /**
     * 保存
     *
     * @param record
     * @return
     */
    @Override
    public int insert(T record) {
        return mapper.insert(record);
    }

    @Override
    public int insertSelective(T record) {
        return mapper.insertSelective(record);
    }

    @Override
    public T selectByPrimaryKey(String id) {
        if (NullUtils.isEmpty(id)) {
            return null;
        }
        return (T) mapper.selectByPrimaryKey(id);
    }

    /**
     * 对非null字段进行更新
     *
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(T record) {
        if (NullUtils.isEmpty(record)) {
            return 0;
        }
        record.setModifyTime(new Date());
        return mapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 对全部字段进行更新
     *
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKey(T record) {
        if (NullUtils.isEmpty(record)) {
            return 0;
        }
        record.setModifyTime(new Date());
        return mapper.updateByPrimaryKey(record);
    }
}
